from rest_framework import viewsets, permissions, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django_filters import rest_framework as filters
from django.utils import timezone
from datetime import timedelta
from django.db import models
from .models import Borrowing
from .serializers import   BorrowingSerializer,BorrowingListSerializer


class BorrowingFilter(filters.FilterSet):
    status = filters.ChoiceFilter(choices=Borrowing.STATUS_CHOICES)
    borrower_id = filters.NumberFilter(field_name='borrower')
    book_id = filters.NumberFilter(field_name='book')
    is_overdue = filters.BooleanFilter(method='filter_overdue')

    class Meta:
        model = Borrowing
        fields = ['status', 'borrower_id', 'book_id', 'is_overdue']

    def filter_overdue(self, queryset, name, value):
        if value:
            return queryset.filter(return_date__isnull=True, due_date__lt=timezone.now())
        return queryset

class BorrowingViewSet(viewsets.ModelViewSet):
    """
    借阅记录视图集
    """
    queryset = Borrowing.objects.all()
    serializer_class = BorrowingSerializer
    permission_classes = [permissions.IsAuthenticated]
    filterset_class = BorrowingFilter
    search_fields = ['book__title', 'book__author', 'borrower__username']

    def get_serializer_class(self):
        """根据操作返回不同的序列化器"""
        if self.action == 'list':
            return BorrowingListSerializer
        return BorrowingSerializer

    def get_queryset(self):
        """根据用户角色过滤借阅记录"""
        user = self.request.user

        # 普通用户只能查看自己的借阅记录
        if not user.is_staff:
            return Borrowing.objects.filter(borrower=user)

        # 管理员可以查看所有借阅记录
        return Borrowing.objects.all()

    @action(detail=True, methods=['post'])
    def renew(self, request, pk=None):
        """
        续借图书
        """
        borrowing = self.get_object()

        # 检查借阅者是否为当前用户或管理员
        if borrowing.borrower != request.user and not request.user.is_staff:
            return Response(
                {'error': '您没有权限续借此图书'}, 
                status=status.HTTP_403_FORBIDDEN
            )

        # 检查是否可以续借（假设只能续借一次，且必须在到期前7天内续借）
        if borrowing.is_overdue():
            return Response(
                {'error': '逾期图书不能续借'}, 
                status=status.HTTP_400_BAD_REQUEST
            )

        days_until_due = (borrowing.due_date - timezone.now()).days
        if days_until_due > 7:
            return Response(
                {'error': '只能在到期前7天内续借'}, 
                status=status.HTTP_400_BAD_REQUEST
            )

        # 延长30天
        borrowing.due_date += timedelta(days=30)
        borrowing.save()

        serializer = self.get_serializer(borrowing)
        return Response(serializer.data)

    @action(detail=False, methods=['get'])
    def my_borrowings(self, request):
        """
        获取当前用户的借阅记录
        """
        user = request.user
        borrowings = Borrowing.objects.filter(borrower=user)

        # 应用过滤器
        for filter_name, filter_value in request.query_params.items():
            if filter_name in BorrowingFilter().filters:
                borrowings = borrowings.filter(**{filter_name: filter_value})

        serializer = self.get_serializer(borrowings, many=True)
        return Response(serializer.data)
